﻿using HARTCalibrationTool.SerialPortManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace HARTCalibrationTool.Commands.BatchCalibrationBoard
{
    public class BatchCaliBoardCMDsSwitchHARTChlCMD : BatchCaliBoardCMDsBase
    {
        public BatchCaliBoardCMDsSwitchHARTChlCMD(SerialPortsBase serialPortManager, string commandName) : base(serialPortManager, commandName)
        { 
            
        }

        protected override async Task SendCMD()
        {
            byte[] cmdBytes = null;
            byte[] data = new byte[1] { (byte)CurrentGroupChannel };

            CMDCode = (byte)BatchCaliBoardCMDID.eSwitchHARTChannel;
            Size = 1;
            Data = data;

            cmdBytes = GetCMDBytes();

            SerialPortsBase.PrintMessage("--> " + Utils.BytesArrayToHexString(cmdBytes, suffix:", "));

            await SerialPortMager.SerialPortWrite(cmdBytes);
        }

        public override async Task ParseResponse(byte[] data)
        {
            if (data[4] == 0x00) // success
            {
                CurrentOpenChannel = (CMDsChannelID)((((uint)data[5]) << 24) | (((uint)data[6]) << 16) | (((uint)data[7]) << 8) | data[8]);
            }
            else
            {
                CurrentOpenChannel = CMDsChannelID.eChannelNull;
            }

            await Task.Run(() => {
                SerialPortsBase.PrintMessage("<-- " + $"{Utils.HexToString(data)}");

                if(CurrentOpenChannel != CMDsChannelID.eChannelNull)
                {
                    SerialPortMager.NotifyObserver(BatchCaliBoardObserversInfo.info["HART Channel Switch"], null);
                }
            });
        }
        public override void OnFailure()
        {

        }

        public override void OnSuccess()
        {

        }

        public override void OnTimeout()
        {

        }
    }

    public class AutoCaliBatchCaliBoardCMDsSwitchHARTChlCMD : BatchCaliBoardCMDsSwitchHARTChlCMD
    {
        public AutoCaliBatchCaliBoardCMDsSwitchHARTChlCMD(SerialPortsBase serialPortManager, string commandName, CMDsChlID chl) : base(serialPortManager, commandName)
        {
            CurrentGroupChannel = chl;
        }

        public override async Task ParseResponse(byte[] data)
        {
            string responseStr = $"{Utils.HexToString(data)}";

            await Task.Run(() => {
                CommandExeSuccess();
                SetCurrentCMDResponseFinishedFlg();

                MainUI.loggerDebugMsg("<--" + responseStr);
                SerialPortsBase.PrintMessage("<-- " + responseStr);
            });
        }
    }
}
